package com.wushi.yangjing;

import java.io.File;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import com.octopus.yangj.generated.model.KnowledgeCategoryStruct;
import com.octopus.yangj.generated.model.KnowledgeStruct;


import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExcelMgt{

	private static ExcelMgt excelMgt;
	
	public static ExcelMgt getInstance(){
		if(excelMgt==null){
			excelMgt=new ExcelMgt();
			}	
		return excelMgt;
	}
	
	/*
	 * In the Web Environment
	 * export the conent to Excel basing on the template.
	 * @see com.wushi.ExcelMgt.ExcelMgtInf#exportExcel(java.io.File, java.io.OutputStream)
	 */
	public void exportExcel(List<KnowledgeStruct> knowledgeList ,File template, OutputStream out) {
		try {
			WorkbookSettings settings = new WorkbookSettings ();
			settings.setWriteAccess(null);
			
			Workbook workbook = Workbook.getWorkbook(template); 
			WritableWorkbook wb = Workbook.createWorkbook(out, workbook, settings);
			WritableSheet ws=wb.getSheet("knowledgeList");
			
			Iterator<KnowledgeStruct> iterator=knowledgeList.iterator();
			KnowledgeStruct know=null;
			int row = 1;
			while(iterator.hasNext()){
				know=(KnowledgeStruct)iterator.next();
				Label label1=new Label(0,row,know.getName());
				ws.addCell(label1);
				Label label2=new Label(1,row,know.getTelphone());
				ws.addCell(label2);
				Label label3=new Label(2,row,know.getAddress());
				ws.addCell(label3);
				Label label4=new Label(3,row,know.getDetail());
				ws.addCell(label4);
				Label label5=new Label(4,row,know.getService());
				ws.addCell(label5);
				Label label6=new Label(5,row,"No");
				if (know.getProvidedId() != null && know.getProvidedId()){
					label6=new Label(5,row,"Yes");
				}
				ws.addCell(label6);
				Label label7=new Label(6,row,"No");
				if(know.getProvidedCert() != null && know.getProvidedCert()){
					label7=new Label(6,row,"Yes");
				}
				ws.addCell(label7);
				StringBuffer categories = new StringBuffer();
				if(know.getCategories() != null){
					for(KnowledgeCategoryStruct category : know.getCategories()){
						categories.append(category.getName());
						categories.append(",");
					}
					Label label8=new Label(7,row,categories.toString());
					if(categories.length() > 0 && ",".equals(categories.substring(categories.length() - 1))){
						categories.substring(0, categories.length() - 1);
						label8=new Label(7,row,categories.substring(0, categories.length() - 1));
					}
					ws.addCell(label8);
				}
				Label label9=new Label(8,row,know.getSummary());
				ws.addCell(label9);
				row++;
			}
			
			wb.write();
			wb.close();
			workbook.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
